package com.car.dao.impl;

import com.car.dao.EmployeeDao;
import com.car.doamin.Employee;
import com.car.utils.JDBCUtil;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class EmployeeDaoImpl implements EmployeeDao {

    /**
     * 新增
     *
     * @param employee 实体类对象
     * @return 影响记录数
     */
    @Override
    public int add(Employee employee) throws Exception {
        String sql = "insert into t_employee(name,age,gender,work_id,salary)\n " + " VALUE(?,?,?,?,?)";
        return JDBCUtil.update(sql,employee.getName(),employee.getAge(),employee.getGender(),employee.getWorkId(),employee.getSalary());
    }

    /**
     * 删除
     *
     * @param id 主键id
     * @return 影响记录数
     */
    @Override
    public int delete(int id) throws Exception {
        String sql = "delete from t_employee where id = ?";
        return JDBCUtil.update(sql, id);
    }

    /**
     * 更改
     *
     * @param employee 实体类对象
     * @return 影响记录数
     */
    @Override
    public int update(Employee employee) throws Exception {
        String sql = "update t_employee set name = ?,age=?,gender=?,work_id=?,salary=? \n " + " where id = ?";
        return JDBCUtil.update(sql, employee.getName(), employee.getAge(), employee.getGender(), employee.getWorkId(), employee.getSalary(), employee.getId());
    }

    /**
     * 查询
     *
     * @param id 主键id
     * @return 影响记录数
     */
    @Override
    public Employee queryById(int id) throws Exception {
        String sql = "select * from t_employee where id = ?";
        return JDBCUtil.query(sql, Employee.class, id);
    }

    /**
     * 查询所有数据
     *
     * @return 查询到的对象
     */
    @Override
    public List<Employee> queryAll() throws Exception {
        String sql = "select * from t_employee";
        return JDBCUtil.queryList(sql, Employee.class);
    }

    @Override
    public Employee findByWorkId(String workId) throws Exception {
        String sql = "select * from t_employee where worl_id = ?";
        return JDBCUtil.query(sql, Employee.class, workId);
    }

    @Override
    public Set<String> findWorKIds() {
        Set<String> res = new HashSet<>();
        try {
            String sql = "select work_id from t_employee";
            List<Employee> employees = JDBCUtil.queryList(sql, Employee.class);
            for (Employee employee : employees) {
                res.add(employee.getWorkId());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return res;
    }
}
